<template>
  <!-- 模板部分保持不变 -->
  <div class="article-detail">
    <Loading v-if="isLoading" />
    
    <template v-else>
      <div v-if="articleDetail?.article" class="content-layout" id="articleBox">
        <main class="article-main">
          <header class="article-header">
            <h1 class="article-title">{{ articleDetail.article.title }}</h1>
            
            <div class="article-meta">
              <div class="author-info">
                <img :src="avatarUrl" 
                     alt="作者头像" 
                     class="author-avatar">
                <div class="author-meta">
                  <span class="author-name">{{ articleDetail.username || '匿名作者' }}</span>
                  <div class="meta-group">
                    <time class="publish-time">
                      <i class="far fa-calendar-alt"></i>
                      {{ formatDate(articleDetail.article.createTime) }}
                    </time>
                    <span class="meta-divider">·</span>
                    <span class="category">
                      <i class="fas fa-folder"></i>
                      {{ articleDetail.categoryName || '未分类' }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </header>

          <article class="article-content" v-html="renderedContent" ref="articleContent"></article>

          <div class="article-footer">
            <div class="tags-section">
              <i class="fas fa-tags"></i>
              <div class="tags-list">
                <router-link 
                  v-for="tag in articleDetail.tags" 
                  :key="tag.id" 
                  :to="`/tag/${tag.tagName}`" 
                  class="tag">
                  {{ tag.tagName }}
                </router-link>
              </div>
            </div>
          </div>
        </main>

        <aside class="article-sidebar">
          <div class="toc-container">
            <div class="toc-header">
              <div class="title-wrapper">
                <i class="fas fa-list"></i>
                <span>目录</span>
                <span class="progress-text">{{ Math.max(0, Math.min(100, readProgress)) }}%</span>
              </div>
            </div>
            <div class="toc-content">
              <div 
                v-for="item in tocItems" 
                :key="item.id" 
                class="toc-item" 
                :class="{
                  'active': activeHeading === item.id,
                  [`level-${item.level}`]: true
                }" 
                @click="scrollToHeading(item.id)">
                {{ item.text }}
              </div>
            </div>
          </div>
        </aside>
      </div>
      
      <div v-else class="not-found">
        <h2>文章不存在</h2>
        <router-link to="/" class="back-link">返回首页</router-link>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick, onUnmounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getArticle } from '@/api/article'
import Loading from '@/components/ui/Loading.vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'
import defaultAvatar from '@/assets/images/default-avatar.webp'
import { marked } from 'marked'
import DOMPurify from 'dompurify'

const route = useRoute()
const router = useRouter()
const articleDetail = ref(null)
const isLoading = ref(false)
const readProgress = ref(0)
const tocItems = ref([])
const activeHeading = ref('')
const articleContent = ref(null)
let observer = null

// 计算属性处理头像URL
const avatarUrl = computed(() => {
  return articleDetail.value?.avatar || defaultAvatar
})

// 计算属性处理Markdown渲染
const renderedContent = computed(() => {
  if (!articleDetail.value?.article?.content) return ''
  const rawMarkdown = articleDetail.value.article.content
  const html = marked(rawMarkdown)
  return DOMPurify.sanitize(html)
})

const fetchArticle = async (id) => {
  isLoading.value = true;
  try {
    const response = await getArticle(id);
    articleDetail.value = response.data;
    
    if (articleDetail.value.article.createTime) {
      articleDetail.value.article.createTime = formatDateTime(articleDetail.value.article.createTime);
    }
    
    await nextTick();
    await setupTocObserver();
    highlightCodeBlocks();
  } catch (error) {
    console.error('获取文章失败:', error);
  } finally {
    isLoading.value = false;
  }
};

const highlightCodeBlocks = () => {
  document.querySelectorAll('pre code').forEach((block) => {
    hljs.highlightElement(block)
  })
}

const generateToc = () => {
  const contentEl = articleContent.value;
  if (!contentEl) {
    console.warn('文章内容容器未找到');
    return;
  }

  const headings = contentEl.querySelectorAll('h1, h2, h3, h4, h5, h6');
  tocItems.value = Array.from(headings).map((heading, index) => {
    const text = heading.textContent
      .replace(/[\u200B-\u200D\uFEFF]/g, '')
      .replace(/\s+/g, ' ')
      .trim();

    const id = `heading-${index}-${text.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')}`;
    
    if (!heading.id) {
      heading.id = id;
    }

    return {
      id: heading.id,
      text,
      level: parseInt(heading.tagName.charAt(1))
    };
  });
};

const setupTocObserver = async () => {
  if (observer) observer.disconnect();

  await nextTick();
  
  setTimeout(() => {
    generateToc();
    
    observer = new MutationObserver((mutations) => {
      if (mutations.some(m => m.type === 'childList')) {
        generateToc();
      }
    });

    if (articleContent.value) {
      observer.observe(articleContent.value, {
        childList: true,
        subtree: true
      });
    }
  }, 100);
};

const scrollToHeading = (id) => {
  const element = document.getElementById(id)
  if (element) {
    const header = document.querySelector('.header')
    const headerHeight = header ? header.offsetHeight : 0
    const offset = headerHeight + 20 // 20px额外间距
    
    const elementPosition = element.getBoundingClientRect().top + window.pageYOffset
    window.scrollTo({
      top: elementPosition - offset,
      behavior: 'smooth'
    })
    
    activeHeading.value = id
  }
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

const formatDate = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-')
}

const updateReadProgress = () => {
  const articleBox = document.getElementById('articleBox')
  if (articleBox) {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop
    const scrollHeight = articleBox.scrollHeight
    const clientHeight = document.documentElement.clientHeight
    readProgress.value = Math.round((scrollTop / (scrollHeight - clientHeight)) * 100)
    
    // 更新目录激活状态
    updateActiveHeading()
  }
}

// 在组件卸载前保存滚动位置
onBeforeUnmount(() => {
  const scrollPosition = window.pageYOffset || document.documentElement.scrollTop
  router.options.scrollBehavior = () => ({ top: scrollPosition })
})

onMounted(() => {
  console.log('当前路由参数:', route.params) // 调试用
  console.log('文章ID:', route.params.id)   // 调试用
  fetchArticle(route.params.id)
  window.addEventListener('scroll', updateReadProgress)
})

onUnmounted(() => {
  if (observer) {
    observer.disconnect()
  }
  window.removeEventListener('scroll', updateReadProgress)
})

watch(() => route.params.id, (newId) => {
  fetchArticle(newId)
})

const updateActiveHeading = () => {
  const headings = tocItems.value.map(item => document.getElementById(item.id))
  const header = document.querySelector('.header') // 修改为你的导航栏类名
  const headerHeight = header ? header.offsetHeight : 0

  // 从最后一个标题开始检查
  for (let i = headings.length - 1; i >= 0; i--) {
    const heading = headings[i]
    if (heading) {
      const rect = heading.getBoundingClientRect()
      // 当标题顶部接近导航栏底部时激活（20px缓冲区域）
      if (rect.top <= headerHeight + 20) {
        activeHeading.value = heading.id
        break
      }
    }
  }
}
</script>

<style scoped>
/* 样式部分保持不变 */
.article-detail {
  padding: 2rem 0;
}

.content-layout {
  display: flex;
  width: 100%;
  margin: 0 auto;
  padding: 0;
}

.article-main {
  width: 800px;
  margin-right: 50px;
  padding: 20px;
}

.author-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid rgba(66, 185, 131, 0.2);
  transition: transform 0.5s ease;
}

.author-avatar:hover {
  transform: rotate(360deg);
  border-color: #42b983;
}

.tags-section {
  display: flex;
  align-items: center;
  margin-top: 2rem;
  padding-top: 1.5rem;
  border-top: 1px solid var(--border-color);
}

.tags-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
  color: var(--text-secondary);
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.8rem;
  margin-left: 0.5rem;
}

.tag {
  padding: 0.4rem 0.8rem;
  background: var(--tag-bg);
  border-radius: 15px;
  font-size: 0.9rem;
  color: var(--tag-color);
  transition: all 0.3s ease;
  text-decoration: none;
}

.tag:hover {
  background: var(--tag-hover-bg);
  color: white;
  transform: translateY(-2px);
}

.tag i {
  margin-right: 5px;
  font-size: 0.9em;
}

.progress-text {
  margin-left: auto;
  color: #42b983;
  font-weight: bold;
  transition: none;
}

.article-header {
  margin-bottom: 2.5rem;
}

.article-title {
  font-size: 2.2rem;
  margin: 0 0 1.5rem;
  line-height: 1.4;
  color: var(--text-primary);
  font-weight: 700;
  position: relative;
  padding-bottom: 0.8rem;
  border-bottom: 1px solid var(--border-color);
}

.article-title::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100px;
  height: 2px;
  background: var(--primary);
}

.author-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.author-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}

.author-name {
  font-weight: 600;
  color: #42b983;
  font-size: 1.1rem;
}

.meta-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.article-content {
  line-height: 1.8;
  color: var(--text-primary);
  font-size: 1.1rem;
  margin-bottom: 2rem;
}

.article-content ::v-deep p {
  margin-bottom: 1.5rem;
}

.article-content ::v-deep h1,
.article-content ::v-deep h2,
.article-content ::v-deep h3,
.article-content ::v-deep h4 {
  margin: 2rem 0 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
}

.article-content ::v-deep h1 {
  font-size: 1.8rem;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 0.5rem;
}

.article-content ::v-deep h2 {
  font-size: 1.6rem;
}

.article-content ::v-deep h3 {
  font-size: 1.4rem;
}

.article-content ::v-deep h4 {
  font-size: 1.2rem;
}

.article-content ::v-deep a {
  color: var(--primary);
  text-decoration: underline;
  transition: color 0.3s ease;
}

.article-content ::v-deep a:hover {
  color: var(--primary-dark);
}

.article-content ::v-deep img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 1.5rem 0;
}

.article-content ::v-deep pre {
  background: var(--code-bg);
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
  margin: 1.5rem 0;
}

.article-content ::v-deep code {
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 0.9em;
  background: var(--code-bg);
  padding: 0.2em 0.4em;
  border-radius: 3px;
}

.article-content ::v-deep blockquote {
  border-left: 4px solid var(--primary);
  background: var(--blockquote-bg);
  padding: 1rem;
  margin: 1.5rem 0;
  color: var(--text-secondary);
}

.tags-section {
  margin-top: 3rem;
  padding-top: 2rem;
  border-top: 1px solid #eee;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.8rem;
  margin-top: 1rem;
}

.tag {
  padding: 0.4rem 0.8rem;
  background: #f0f7ff;
  border-radius: 15px;
  font-size: 0.9rem;
  color: #1890ff;
  transition: all 0.3s ease;
  text-decoration: none;
}

.tag:hover {
  background: #1890ff;
  color: white;
}

.article-sidebar {
  width: 350px;
  position: fixed;
  right: calc((100% - 1400px) / 2 + 50px);
  top: 100px;
}

.toc-container {
  width: 350px;
  height: 50vh;
  overflow-y: auto;
  background: white;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.toc-header {
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #eee;
}

.toc-item {
  padding: 0.5rem 0;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #666;
}

.toc-item:hover {
  color: #42b983;
}

.toc-item.active {
  color: #42b983;
  font-weight: 500;
}

.toc-item.level-2 {
  padding-left: 1rem;
}

.toc-item.level-3 {
  padding-left: 2rem;
}

.progress-text {
  margin-left: 10px;
  color: #42b983;
  font-weight: bold;
}

.not-found {
  text-align: center;
  padding: 2rem;
}

.back-link {
  display: inline-block;
  margin-top: 1rem;
  color: #42b983;
  text-decoration: none;
}
</style>